#include "include.h"

static sdadc_cfg_t mic_cfg = {CH_MICL0,  (3 << 6),   SPR_48000,    ADC2DAC_EN,    128,    NULL};
volatile bool sdadc_w4_kick;

AT(.text.bsp.wireless_mic)
void mic_init(u8 sample_rate, u16 samples)
{
    mic_cfg.sample_rate = sample_rate;
    mic_cfg.samples = samples*2;
    mic_channel_get_param(&mic_cfg.channel, &mic_cfg.gain);
    //软件数字增益
    soft_gain_set(xcfg_cb.mic_soft_gain);

    //这里先注释掉，在callback_set中设置callback函数后再初始化
//    sdadc_init(&mic_cfg);
//    sdadc_start(mic_cfg.channel);
}

AT(.text.bsp.wireless_mic)
void mic_audio_output_callback_set(audio_callback_t callback)
{
    mic_cfg.callback = callback;

    //改到蓝牙连接后再初始化，节省未连接功耗
//    sdadc_init(&mic_cfg);
//    sdadc_start(mic_cfg.channel);
}

AT(.text.bsp.wireless_mic)
void mic_start(void)
{
    sdadc_init(&mic_cfg);
    sdadc_start(mic_cfg.channel);

    /// DC 去直流 关闭高通滤波器 恢复一些低频信号
    #if DEVICE_MIC_DC_EN
    #define SDADCDIGCON     SFR_RW (SFR1_BASE + 0x37*4)
    SDADCDIGCON &= ~(BIT(29) | BIT(30));
    SDADCDIGCON |= BIT(22) | BIT(23);
    SDADCDIGCON |= (BIT(1) | BIT(9));
    #endif

    sdadc_w4_kick = true;
}

AT(.com_text.bsp.wireless_mic)
void wireless_mic_kick(void)
{
    if (sdadc_w4_kick) {
        sdadc_w4_kick = false;
        sdadc_start_kick(mic_cfg.channel);
    }
}

AT(.text.bsp.wireless_mic)
void mic_stop(void)
{
    sdadc_exit(mic_cfg.channel);
}

#if ADAPTER_LOACL_MIC_EN
// PF3 --> ADC --> MIC_EQ --> MIC_DRC --> SRC1_DAC
//                                    |-->MIC_MIX --> SRC0_DAC --> USB_MIC
AT(.text.bsp.wireless_mic)
void local_mic_init(void)
{
    mic_init(WIRELESS_MIC_SAMPLE_RATE_SELECT, WIRELESS_MIC_SAMPLES_SELECT);
    mic_audio_output_callback_set(mic_eq_drc_audio_input);

    //初始化EQ_DRC
    mic_eq_drc_init(WIRELESS_MIC_SAMPLE_RATE_SELECT, WIRELESS_MIC_SAMPLES_SELECT);
#if ADAPTER_LOCAL_MIC_MIX_EN
    //进入MIC_MIX
    mic_eq_drc_audio_output_callback_set(mic_mix_process_cb);
#else
    //直通DAC
    mic_eq_drc_audio_output_callback_set(dac1_out_audio_input);
    dac1_out_init(WIRELESS_MIC_SAMPLE_RATE_SELECT, WIRELESS_MIC_SAMPLES_SELECT);
#endif
#if !DEVICE_MIX_AUX_EN
    mic_start();
#else
    mic_mix_aux_start();
#endif
    sdadc_start_kick(CH_MICR0);

}
#endif
